/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.forum.ui;

import com.alee.extended.image.DisplayType;
import com.alee.extended.image.WebImage;
import com.alee.extended.label.WebLinkLabel;
import com.alee.extended.layout.HorizontalFlowLayout;
import com.alee.extended.panel.GroupPanel;
import com.alee.extended.panel.WebButtonGroup;
import com.alee.laf.button.WebButton;
import com.alee.laf.label.WebLabel;
import com.alee.laf.panel.WebPanel;
import com.alee.managers.hotkey.Hotkey;
import com.alee.managers.hotkey.HotkeyInfo;
import com.alee.managers.hotkey.HotkeyManager;
import com.alee.managers.hotkey.HotkeyRunnable;
import com.alee.managers.popup.PopupListener;
import com.alee.managers.popup.PopupManager;
import com.alee.managers.popup.WebPopup;
import com.alee.managers.tooltip.TooltipManager;
import com.alee.managers.tooltip.TooltipWay;
import com.alee.utils.SwingUtils;
import com.alee.utils.SystemUtils;
import com.alee.utils.WebUtils;
import com.alee.utils.collection.ValuesTable;
import com.rag.core.Item;
import com.rag.utils.RagUtils;
import info.clearthought.layout.TableLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * User: mgarin Date: 10.04.12 Time: 16:54
 */

public class ItemPopup extends WebPopup
{
    private static ImageIcon typeIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/type.png" ) );
    private static ImageIcon prefixIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/prefix.png" ) );
    private static ImageIcon levelIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/level.png" ) );
    private static ImageIcon weightIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/weight.png" ) );
    private static ImageIcon sellIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/sell.png" ) );
    private static ImageIcon buyIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/buy.png" ) );
    private static ImageIcon weaponLevelIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/weaponLevel.png" ) );
    private static ImageIcon attackIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/attack.png" ) );
    private static ImageIcon defenceIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/defence.png" ) );
    private static ImageIcon copyIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/copy.png" ) );
    private static ImageIcon nameIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/name.png" ) );
    private static ImageIcon codeIcon =
            new ImageIcon ( ItemPopup.class.getResource ( "icons/info/code.png" ) );

    private HotkeyInfo escapeHotkey;

    public ItemPopup ( Item item )
    {
        super ();
        setMargin ( 10 );
        add ( createItemDescription ( item ) );

        // Для быстрого закрытия попапа по ESC
        addPopupListener ( new PopupListener ()
        {
            public void popupOpened ()
            {
                escapeHotkey = HotkeyManager
                        .registerHotkey ( ItemPopup.this, Hotkey.ESCAPE, new HotkeyRunnable ()
                        {
                            public void run ( KeyEvent e )
                            {
                                ItemPopup.this.hidePopup ();
                            }
                        } );
            }

            public void popupClosed ()
            {
                HotkeyManager.unregisterHotkey ( escapeHotkey );
                escapeHotkey = null;
            }
        } );
    }

    public static WebPanel createItemDescription ( final Item item )
    {
        int gap = 10;

        ValuesTable<JComponent, JComponent> table = new ValuesTable<JComponent, JComponent> ();

        // Показываем название итема со ссылкой на сайт с базой

        WebLinkLabel itemLink = RagUtils.createItemLink ( item );
        //itemLink.setForeground ( Color.BLACK );

        final WebLinkLabel idLabel = RagUtils.createIdLink ( item );

        WebButton motr = WebButton.createIconWebButton ( ServerIcons.motr );
        TooltipManager.setTooltip ( motr, "Итем в МОТР базе", TooltipWay.up );
        motr.addActionListener ( new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                WebUtils.browseSiteSafely ( item.getMotrLink () );
            }
        } );

        WebButton iro = WebButton.createIconWebButton ( ServerIcons.iro );
        TooltipManager.setTooltip ( iro, "Итем в IroWiki базе", TooltipWay.up );
        iro.addActionListener ( new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                WebUtils.browseSiteSafely ( item.getIroLink () );
            }
        } );

        WebButton rms = WebButton.createIconWebButton ( ServerIcons.rms );
        TooltipManager.setTooltip ( rms, "Итем в RateMyServer базе", TooltipWay.up );
        rms.addActionListener ( new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                WebUtils.browseSiteSafely ( item.getRatemyserverLink () );
            }
        } );

        WebButtonGroup linkGroup = new WebButtonGroup ( motr, rms, iro );
        linkGroup.setButtonsMargin ( 1 );
        linkGroup.setButtonsDrawFocus ( false );

        WebButton copy = WebButton.createIconWebButton ( copyIcon );
        TooltipManager.setTooltip ( copy, "Копировать итем", TooltipWay.up );
        copy.addActionListener ( new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                RagUtils.copyToClipboard ( item );
            }
        } );

        WebButton name = WebButton.createIconWebButton ( nameIcon );
        TooltipManager.setTooltip ( name, "Копировать имя итема", TooltipWay.up );
        name.addActionListener ( new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                SystemUtils.copyToClipboard ( item.getTitle () );
            }
        } );

        WebButton code = WebButton.createIconWebButton ( codeIcon );
        TooltipManager
                .setTooltip ( code, "Копировать BB-code итема для МОТР форума", TooltipWay.up );
        code.addActionListener ( new ActionListener ()
        {
            public void actionPerformed ( ActionEvent e )
            {
                SystemUtils.copyToClipboard ( RagUtils.getItemCode ( item ) );
            }
        } );

        WebButtonGroup copyGroup = new WebButtonGroup ( copy, name, code );
        copyGroup.setButtonsMargin ( 1 );
        copyGroup.setButtonsDrawFocus ( false );

        table.put ( new WebLabel ( "Название", WebLabel.RIGHT ),
                new GroupPanel ( gap, itemLink, idLabel, linkGroup, copyGroup ) );

        // Специфичные параметры
        WebPanel generalPanel = new WebPanel ( new HorizontalFlowLayout ( gap ) );
        generalPanel.setOpaque ( false );
        if ( item.getItemType () != null )
        {
            WebLabel label = new WebLabel ( item.getItemType ().getTypeName () + " - " +
                    item.getItemClass ().getClassName (), typeIcon );
            TooltipManager.setTooltip ( label, typeIcon, "Тип и класс", TooltipWay.up );
            generalPanel.add ( label );
        }
        if ( item.getCardSuffix () != null )
        {
            WebLabel label = new WebLabel ( item.getCardSuffix (), prefixIcon );
            TooltipManager
                    .setTooltip ( label, prefixIcon, "Суффикс/префикс карточки", TooltipWay.up );
            generalPanel.add ( label );
        }
        if ( !RagUtils.isCard ( item ) )
        {
            if ( item.getWeight () != null )
            {
                String weightText = ( "" + item.getWeight () ).replaceAll ( "\\.0", "" );
                WebLabel label = new WebLabel ( weightText, weightIcon );
                TooltipManager.setTooltip ( label, weightIcon, "Вес итема", TooltipWay.up );
                generalPanel.add ( label );
            }
            if ( item.getSellPrice () != null )
            {
                WebLabel label = new WebLabel ( item.getSellPrice () + "z", sellIcon );
                TooltipManager.setTooltip ( label, sellIcon, "Цена при продаже итема в магазин",
                        TooltipWay.up );
                generalPanel.add ( label );
            }
            if ( item.getBuyPrice () != null )
            {
                WebLabel label = new WebLabel ( item.getBuyPrice () + "z", buyIcon );
                TooltipManager.setTooltip ( label, buyIcon, "Цена при покупке итема в магазине",
                        TooltipWay.up );
                generalPanel.add ( label );
            }
            if ( item.getRequiredLvl () != null && item.getRequiredLvl () > 1 )
            {
                WebLabel label = new WebLabel ( "" + item.getRequiredLvl (), levelIcon );
                TooltipManager
                        .setTooltip ( label, levelIcon, "Требуемый для экипировки базовый уровень",
                                TooltipWay.up );
                generalPanel.add ( label );
            }
            if ( item.getWeaponLvl () != null )
            {
                WebLabel label = new WebLabel ( "" + item.getWeaponLvl (), weaponLevelIcon );
                TooltipManager
                        .setTooltip ( label, weaponLevelIcon, "Уровень оружия", TooltipWay.up );
                generalPanel.add ( label );
            }
            if ( item.getAttack () != null && item.getAttack () > 0 )
            {
                WebLabel label = new WebLabel ( "" + item.getAttack (), attackIcon );
                TooltipManager.setTooltip ( label, attackIcon, "Атака", TooltipWay.up );
                generalPanel.add ( label );
            }
            if ( item.getDefense () != null && item.getDefense () > 0 )
            {
                WebLabel label = new WebLabel ( "" + item.getDefense (), defenceIcon );
                TooltipManager.setTooltip ( label, defenceIcon, "Защита", TooltipWay.up );
                generalPanel.add ( label );
            }
        }
        if ( generalPanel.getComponentCount () > 0 )
        {
            table.put ( new WebLabel ( "Общее", WebLabel.RIGHT ), generalPanel );
        }

        //        // Показываем подробные поля для всех итемов кроме карточек
        //        if ( !RagUtils.isCard ( item ) )
        //        {
        //
        //            // Специфичные параметры
        //            WebPanel specificPanel = new WebPanel ( new HorizontalFlowLayout ( gap ) );
        //            if ( specificPanel.getComponentCount () > 0 )
        //            {
        //                table.put ( new WebLabel ( "Экипировка", WebLabel.RIGHT ), specificPanel );
        //            }
        //        }

        // Описание
        table.put ( new WebLabel ( "Описание", WebLabel.RIGHT ), getDescription ( item ) );

        // Скрипт
        table.put ( new WebLabel ( "Скрипт", WebLabel.RIGHT ),
                new WebLabel ( "<html>" + item.getScript () + "</html>" ) );

        WebPanel descriptionPanel = RagUtils.createTable ( TableLayout.PREFERRED, gap, table );

        final ImageIcon image = RagUtils.getItemImage ( item );
        if ( image != null && image.getImage () != null )
        {
            WebPanel cardImagePanel = new WebPanel ( new BorderLayout ( 10, 10 ) );
            cardImagePanel.setOpaque ( false );
            cardImagePanel.add ( descriptionPanel, BorderLayout.CENTER );
            cardImagePanel.add ( createImageView ( image, item ), BorderLayout.EAST );
            return cardImagePanel;
        }
        else
        {
            return descriptionPanel;
        }
    }

    private static JComponent getDescription ( final Item item )
    {
        //        if ( item.getIroDescription () != null )
        //        {
        //            final WebEditorPane webEditorPane = new WebEditorPane ()
        //            {
        //                protected void paintComponent ( Graphics g )
        //                {
        ////                    LafUtils.setupAntialias ( g );
        //                    super.paintComponent ( g );
        //                }
        //            };
        //
        //            // add an html editor kit
        //            HTMLEditorKit kit = new HTMLEditorKit ();
        //            webEditorPane.setEditorKit ( kit );
        //
        //            // add some styles to the html
        //            StyleSheet styleSheet = kit.getStyleSheet ();
        //            styleSheet.addRule (
        //                    "ul { list-style-position: inside; text-indent: 5px; padding: 6px; margin-left: 2px; margin-right: 2px; margin-top: 0; margin-bottom: 0; }" );
        //            //            styleSheet.addRule ( "li { margin: 0px; }" );
        //
        //            // create a document, set it on the jeditorpane, then add the html
        //            Document doc = kit.createDefaultDocument ();
        //            webEditorPane.setDocument ( doc );
        //            webEditorPane.setText ( item.getIroDescription () );
        //
        //            webEditorPane.setFont ( new WebLabel ().getFont () );
        //            webEditorPane.setEditable ( false );
        //            webEditorPane.setOpaque ( false );
        //            webEditorPane.addHyperlinkListener ( new HyperlinkListener ()
        //            {
        //                private String start = "/db/item-info/";
        //
        //                public void hyperlinkUpdate ( HyperlinkEvent e )
        //                {
        //                    if ( e.getEventType () == HyperlinkEvent.EventType.ACTIVATED )
        //                    {
        //                        String href = e.getURL ().toExternalForm ();
        //                        href = href.substring ( href.indexOf ( start ) + start.length () );
        //                        href = href.substring ( 0, href.length () - 1 );
        //
        //                        RagUtils.showItemPopup (
        //                                SwingUtils.getWindowAncestor ( TradeHelper.getInstance () ), href );
        //                    }
        //                }
        //            } );
        //            return webEditorPane;
        //        }
        //        else
        //        {
        return new WebLabel (
                item.getDescription () != null ? "<html>" + item.getDescription () + "</html>" :
                        "Нет описания" );
        //        }
    }

    private static WebImage createImageView ( final ImageIcon image, final Item item )
    {
        final WebImage imageComponent = new WebImage ( image )
        {
            public Dimension getPreferredSize ()
            {
                Container parent = getParent ();
                Dimension ps = super.getPreferredSize ();

                int w = ps.width;
                int h = ps.height;
                ps.width = Math.min ( w * parent.getHeight () / h, image.getIconWidth () );
                ps.height = 0;

                return ps;
            }
        };
        imageComponent.setDisplayType ( DisplayType.fitComponent );
        if ( RagUtils.isCard ( item ) )
        {
            imageComponent.setCursor ( Cursor.getPredefinedCursor ( Cursor.HAND_CURSOR ) );
            imageComponent.addMouseListener ( new MouseAdapter ()
            {
                public void mousePressed ( MouseEvent e )
                {
                    if ( SwingUtilities.isLeftMouseButton ( e ) )
                    {
                        final WebPopup popup = new WebPopup ();
                        popup.add ( new WebImage ( image )
                        {
                            {
                                setCursor ( Cursor.getPredefinedCursor ( Cursor.HAND_CURSOR ) );
                                addMouseListener ( new MouseAdapter ()
                                {
                                    public void mousePressed ( MouseEvent e )
                                    {
                                        RagUtils.showItemPopup (
                                                SwingUtils.getWindowAncestor ( popup ), item );
                                    }
                                } );
                            }
                        }, BorderLayout.CENTER );
                        PopupManager.showModalPopup ( imageComponent, popup, false, false );
                    }
                }
            } );
        }
        return imageComponent;
    }

    public Dimension getPreferredSize ()
    {
        Dimension ps = super.getPreferredSize ();
        ps.width = Math.min ( ps.width, getParent ().getWidth () );
        ps.height = Math.min ( ps.height, getParent ().getHeight () );
        return ps;
    }
}